import { _decorator, Component, instantiate, Layers, Layout, Node, Prefab, resources, RichText, Sprite, SpriteAtlas, UITransform, Vec3 } from 'cc';
import { IPokerVo, Poker } from '../data/Poker';
import  CardCtrl  from '../controllers/CardCtrl';
import  TimerCtrl  from '../controllers/TimerCtrl';
import PokerUtil from '../utils/PokerUtil';
import PromiseUtil from '../utils/PromiseUtil';
// import CardGameCtrl from '../controllers/CardGameCtrl';
const { ccclass, property } = _decorator;

@ccclass('GameMgr')
export default class GameMgr extends Component {

    // 已出的牌父节点
    @property(Node)
    cardsPlayedParent: Node = null
    // 玩家手牌父节点，用于本机用户手牌预制体
    @property(Node)
    handCardsParent: Node = null

    // 牌预制体
    @property(Prefab)
    cardPrefab: Prefab = null

    // 定时器预制体
    @property(Prefab)
    timerPrefab: Prefab = null
    // 定时器
    @property(Node)
    timerParent: Node = null

    private localPlayerIndex: number = 0            // 本机玩家下标
    private selectdCards: Set<Poker> = new Set()    //本机玩家选择的手牌

    start() {
        this.init();// 初始化

    }

    init() {
        this.selectdCards = new Set()

        
    }

    
    /**
     * 按钮点击事件
     */
    async onSendCardBtnClickEvent() {
        
        console.log('onSendCardBtnClickEvent')

        this.clearCardsPlayed();// 清空已出的牌
        this.sendHandCards();//显示牌

        
        this.showTimer(null, 1, 3);// 显示闹钟定时器
        await PromiseUtil.sleep(10);//等待10s
        this.clearTimer();//清空闹钟定时器

    }
    
    private sendHandCards() {
        const data: { uid: string, cards: Array<IPokerVo> } = {
            uid: "123456",
            cards: [{suit: 1, point: 11},{suit: 1, point: 12},{suit: 1, point: 13}],
        }
        // console.log("data===========")
        // console.log(data)
        // 数据对象转为扑克对象
        const cards = data.cards.map(card => new Poker(card))

        // 排序
        PokerUtil.sort(cards)

        this.showPoker(cards);// 显示玩家手牌
        
    }


    /**
     * 显示玩家手牌
     */
    private showPoker(cards: Array<Poker>) {
        // console.log("showPoker-----")
        // 移除所有子节点
        this.handCardsParent.removeAllChildren()
        console.log("for开始-=========================")
        
        for (let i = 0; i < cards.length; i++) {
            const poker = cards[i]

            // 创建牌预制体
            let cardNode = instantiate(this.cardPrefab)
            // console.log("------------cardNode--------", cardNode)
            
            // cardNode.setScale(1, 1, 1);//牌缩放
            let cardCtrl = cardNode.getComponent(CardCtrl)
            this.handCardsParent.addChild(cardNode)
            this.handCardsParent.children[i].layer = Layers.Enum.UI_2D;//这个问题特别注意

            cardCtrl.init(poker)    // 初始化牌预制体数据


            // 牌触摸事件
            cardCtrl.addTouchListener((poker: Poker, isSelected: boolean) => {
                console.log("GameCtrl->cardCtrl.addTouchListener-=========================")
                console.log('isSelected:', isSelected)
                console.log('poker:', poker)
                // 保存已选择的牌
                if (this.selectdCards.has(poker)) {
                    this.selectdCards.delete(poker)
                } else {
                    this.selectdCards.add(poker)
                }
                console.log('selectdCards:', this.selectdCards)
            })
        }
        console.log("for结束-=========================")
    }

    

    /**
     * 清空玩家手牌
     */
    private clearPoker() {
        // 移除所有子节点
        this.handCardsParent.removeAllChildren()
    }

    /**
     * 删除玩家手牌
     * @param cards
     * @returns 删除的节点
     */
    private deletePoker(cards: Array<Poker>) {
        const handCardsNodeArr = this.handCardsParent.children
        cards.forEach(card => {
            for (let i = 0; i < handCardsNodeArr.length;) {
                const cardCtrl = handCardsNodeArr[i].getComponent(CardCtrl)
                if (cardCtrl.poker == card) {
                    // 删除
                    this.handCardsParent.removeChild(handCardsNodeArr[i])
                } else {
                    i++
                }
            }
        })
    }

    /**
     * 显示出的牌
     * @param cards 
     */
    private showCardsPlayed(cards: Array<Poker>) {
        this.clearCardsPlayed()
        cards.forEach(card => {
            const cardNode = instantiate(this.cardPrefab)
            const cardCtrl = cardNode.getComponent(CardCtrl)
            cardCtrl.init(card)
            cardCtrl.touchEnable = false
            cardNode.setScale(0, 0.7, 0)
            this.cardsPlayedParent.addChild(cardNode)
        })
    }

    /**
     * 清除显示出的牌
     */
    private clearCardsPlayed() {
        this.cardsPlayedParent.removeAllChildren()
    }

     /**
     * 显示定时器
     * @param seatNum 
     */
     private showTimer(callback: Function, seatNum: number, delay: number = 20) {
        if (!(seatNum >= 1 && seatNum <= 3)) {
            throw new Error(`seatNum:${seatNum}. seatNum not 1~3. `)
        }

        // 创建定时器节点
        const timerNode = instantiate(this.timerPrefab)
        const timerCtrl = timerNode.getComponent(TimerCtrl)

        // 添加节点
        const seatNode = this.timerParent.children[seatNum - 1]
        seatNode.removeAllChildren()
        seatNode.addChild(timerNode)
        // console.log("timerNode: ", timerNode);
        // console.log("seatNode: ", seatNode);

        // 初始化定时器
        timerCtrl.init(delay)
        timerCtrl.addTimeoutListener(callback)
    }

    /**
     * 关闭指定位置的定时器
     * @param seatNum 
     */
    private offTimer(seatNum: number) {
        this.timerParent.children[seatNum - 1].children.forEach(node => {
            node.destroy()
        })
    }

    /**
     * 清空所有定时器
     */
    private clearTimer() {
        this.timerParent.children.forEach(seatNode => {
            seatNode.children.forEach(node => {
                node.destroy()
            })
        })
    }

    //---------触摸------start
    

    //---------触摸------end



}


